package com.hx.myblog3.control.admin;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hx.myblog3.entity.Article;
import com.hx.myblog3.entity.ArticleType;
import com.hx.myblog3.service.ArticleService;
import com.hx.myblog3.service.ArticleTypeService;

@Controller
@RequestMapping("/admin")
public class ArticleControl {
	@Autowired
	private ArticleService as;
	@Autowired
	private ArticleTypeService ats;
	
	@RequestMapping("/update")
	@ResponseBody//返回Json数据
	public String updateArticle(@RequestParam("typeid") Integer typeid,Article article){
		ArticleType atype=ats.findOne(typeid);
		article.setAtype(atype);
		as.update(article);
		return "成功！";
	}
	
	
	@RequestMapping("/allarticles")
	@ResponseBody
	public List<Map<String, Object>> allArticles(){
		return as.allArticles();
	}
	
	@RequestMapping("/info")
	@ResponseBody
	public Article articleInfe(@RequestParam("id") Integer id){
		return as.findone(id);
	}
	
	@RequestMapping("/articleSave")
	@ResponseBody
	public String saveArticle(@RequestParam("typeid") Integer typeid,Article article){
		try {
			Date time=new Date();
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String t=sdf.format(time).toString();
			article.setCreateTime(t);
			ArticleType at=ats.findOne(typeid);
			article.setAtype(at);
			as.save(article);
			return "保存成功";
		} catch (Exception e) {
			return "保存失败";
		}
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public String delArticle(@RequestParam("id") Integer id){
		try {
			as.del(id);
			return "删除成功！";
		} catch (Exception e) {
			e.printStackTrace();
			return "删除失败！";		
		}
	}
		
	@RequestMapping("/getpage/{id}")
	@ResponseBody
	public String getPage(@PathVariable("id") Integer pid){
		Page<Article> page=as.findPage(pid);
		return as.pageToJsonString(page);	
	} 
	
	/*@RequestMapping("/getPageByTypeid")
	@ResponseBody
	public String getPageByType(@RequestParam("id") Integer id,
			@RequestParam("pageno") Integer pageNo){
		Page<Article> page=as.findByAtype(id, pageNo);
		return as.pageToJsonString(page);	
	}*/
	@RequestMapping("/getPageByTypeid/{pageno}")
	@ResponseBody
	public String getPageByType(@RequestParam("id") Integer id,
			@PathVariable("pageno") Integer pageNo){
		Page<Article> page=as.findByAtype(id, pageNo);
		return as.pageToJsonString(page);	
	}
	
}
